package com.app.service.impl;

import com.app.mapper.CarPrivateMapper;
import com.app.model.CarPrivateModel;
import com.app.service.CarPrivateService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CarPrivateServiceImpl implements CarPrivateService {
    @Autowired
    private CarPrivateMapper carPrivateMapper;

    @Override
    public void update(CarPrivateModel carModel) {
        carPrivateMapper.updateById(carModel);
    }

    @Override
    public void insert(CarPrivateModel carModel) {
        carPrivateMapper.insert(carModel);
    }

    @Override
    public void delete(Integer id) {
        carPrivateMapper.deleteById(id);
    }

    @Override
    public Page<CarPrivateModel> selectCarList(Integer page, Integer limit, String name, Integer departmentId, Integer sortType) {
        Page<CarPrivateModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        QueryWrapper<CarPrivateModel> queryWrapper = new QueryWrapper<>();
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("car_number", name);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number").orderByDesc("create_time");
        }else {
            queryWrapper.orderByDesc("number").orderByDesc("create_time");
        }
        return carPrivateMapper.selectPage(pages, queryWrapper);
    }
//批量删除车辆信息
    @Override
    public Result<Object> deleteCarBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            carPrivateMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }
}
